<template>
  <div>
    <!-- 
      :headers="upload.headers"
      :action="upload.url"
     -->
    <!-- <el-upload
      class="upload-demo"
      :on-progress="handleFileUploadProgress"
      action="void"
      :http-request="customUpload"
      :on-remove="removeFiles"
      :before-upload="beforecheckfile"
      name="file"
      :file-list="addform.fileList"
      :disabled="upload.isUploading"
      :show-file-list="false"
      accept=".rar,.zip,.doc,.docx,.pdf"
    >
      <el-button
        class="uploadBtn"
        icon="el-icon-upload"
        :disabled="upload.isUploading"
        >上传文件</el-button
      >
      <div slot="tip" class="el-upload__tip">
        支持扩展名：.rar .zip .doc .docx .pdf,大小不超过50M
      </div>
    </el-upload>
    <div
      v-for="(item, index) in addform.fileList"
      :key="index"
      style="
            width:400px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            color: #606266;
            padding-bottom: 0px;
          "
    >
      <span style="font-size: 12px"
        ><i class="el-icon-paperclip"></i> {{ item.fileName }}
      </span>
      <i
        class="el-icon-circle-close delicon"
        @click="delfiledata(index)"
      ></i>
    </div>
    <el-input
      v-model.trim="addform.complaintfilelistvalidator"
      style="display: none"
    ></el-input> -->
    <el-upload
      class="upload-demo"
      ref="upload"
      action="void"
      :http-request="customUpload"
      :on-remove="removeFiles"
      :on-progress="handleFileUploadProgress"
      :file-list="fileList"
      :before-upload="beforecheckfile"
      multiple
      :auto-upload="true"
      :limit='6'
      :on-exceed="exceedLimit"
      :disabled="upload.isUploading"
      :on-error="uploadError"
      accept=" .rar, .zip, .doc, .docx, .pdf">
      <el-button 
        slot="trigger" 
        size="small" 
        type="primary"
        class="uploadBtn"
        icon="el-icon-upload"
        :disabled="upload.isUploading"
      >
        上传文件
      </el-button>
      <div slot="tip" class="el-upload__tip">
        支持扩展名：.rar .zip .doc .docx .pdf,大小不超过50M
      </div>
    </el-upload>
  </div>
</template>

<script>
import hostqt from "@/common/api/service.js";
// import { customUpload } from "@/common/api/service.js";

export default {
  data() {
    return {
      fileList: [],
      addform: {
        fileList: [], //附件资料
        complaintfilelistvalidator: "",
        file: []
      },
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
         // 设置上传的请求头部
        headers: { 'X-Base-Token': localStorage.getItem("qtToken") },
        // 上传的地址
        url: hostqt + "/commerce/comment/uploadFile"
      },
      batchId: "",
      addformrules: {},
      name: ''
    };
  },
  methods: {
    // 上传文件失败
    uploadError(err, file, fileList){
      console.log(err)
      this.message.error("上传文件失败");
    },
    // 超过最大上传数时候触发
    exceedLimit(){
      this.$message.error('最多只能上传6个文件');
    },
    customUpload(file){
      let FormDatas = new FormData();
      FormDatas.append('file', file.file);
      console.log("file外",file)
      // let res = customUpload(FormDatas,file)
      this.axios({
        url: this.upload.url,
        method: 'post',
        headers: this.upload.headers,
        data: FormDatas,
        //上传进度
        onUploadProgress: (progressEvent) => {
            console.log('progressEvent', progressEvent)
            let num = progressEvent.loaded / progressEvent.total * 100 | 0;  //百分比
            file.onProgress({percent: num})     //进度条
        }
      }).then(res => {
            this.upload.open = false;
            this.upload.isUploading = false;
            // console.log('response', response)
          if (res.status == 200) {
            this.addform.file = res.data;
            let obj = {
              fileName: this.name,
              fileType: 2,
              fileUrl: res.data.result
            }
            console.log('file123',obj)
            this.getFileDataList(obj);
            // this.addComloaintsFiles(response);
          }
          // file.onProgress({percent: 0})
          file.onSuccess(); //上传成功(打钩的小图标)
          
      }).catch(err=>{
        // console.log("err",err)
        this.$message.error("文件上传失败")
        console.log(this.addform.fileList)
        this.upload.isUploading = false
      })
    },
    //删除后
    removeFiles(response, fileList) {
      // console.log('删除', fileList)
      let data = fileList;
      this.addComloaintsFiles(data);
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.name = file.name
      this.upload.open = true;
      this.upload.isUploading = true;
    },
    //上传附件前限制大小 格式
    beforecheckfile(file) {
      this.upload.open = true;
      this.upload.isUploading = true;
      let isfile = true;
      var testmsg = file.name.substring(file.name.lastIndexOf(".") + 1);
      let fileformat = ["rar", "zip", "doc", "docx", "pdf"];
      const isLt10M = file.size / 1024 / 1024 < 50;
      isfile = fileformat.includes(String(testmsg));
      if (!isfile) {
        this.$message.error("上传文件格式不正确");
      } else if (!isLt10M) {
        isfile = false;
        this.$message.error("上传文件大小不能超过 50M");
      }
      this.upload.open = false;
      this.upload.isUploading = false;
      return isfile;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      console.log('response', response)
      if (response.status == 200) {
        this.addform.file = response.data;
        
       let obj = {
          fileName: file.name,
          fileType: 2,
          fileUrl: response.result
        }
        console.log('file123',obj)
        this.getFileDataList(obj);
        this.addComloaintsFiles(fileList);
      } else {
        this.$alert(response.message, "上传文件", {});
      }
    },
    //诉求新增文件
    addComloaintsFiles(fileList) {
      // console.log('诉求新增文件', fileList)
      if (fileList.length > 0) {
        this.addform.complaintfilelistvalidator = "yes";
      } else {
        this.addform.complaintfilelistvalidator = "";
      }
    },
    //删除文件
    delfiledata(idx) {
      this.addform.fileList.splice(idx,1)
    },
    //获取附件列表
    getFileDataList(id) {
      this.addform.fileList.push(id)
      this.$emit("changeUp", this.addform.fileList);
    }
  }
};
</script>

<style scoped>
.uploadBtn {
  background-color: #f1f2f4;
  color: #045db9;
  border-width: 0;
  padding: 12px 20px;
  font-size: 14px;
}
</style>
